// import { getImageBySrc } from './mcommon.js';


class Card {
  constructor(obj) {
    let c = {
      name: obj.name,
      canGrow: true,
      canClick: true,
      img: null,
      sun_val: obj.sun_val,
      timer_num: 0,
      isspacing: false,
      timer_spacing: obj.timer_spacing,
      timer: null,
      x: 0,
      y: 0,
      w: 0,
      h: 0,
      blacky: 0,
      blackh: 0,
      lastUpdateTime: 0,
      hasCollided: false
    }
    Object.assign(this, c);
  }

  static new(obj) {
    let b = new this(obj);
    b.init(obj);
    return b;
  }

  init(obj) {
    this.w = 50
    this.h = 63
    this.x = obj.x
    this.y = obj.y
    this.blacky = obj.y
    this.blackh = 63
    this.img = getImageBySrc(allImgSrcObj.plantCard[obj.name].src)
  }

  draw(cxt) {
    let self = this
    const now = Date.now();
    if (!self.hasCollided) {
      self.lastUpdateTime = now
      self.hasCollided = true
    }

    // 计算时间差
    let deltaTime = now - self.lastUpdateTime;
    // console.log(deltaTime)
    if (self.blackh > 0) {
      self.blackh = (self.timer_spacing - deltaTime) / self.timer_spacing * self.h
    }
    self.blacky = self.y + deltaTime / self.timer_spacing * self.h

    this.sun_val > window.main.allSun ? this.canGrow = false : this.canGrow = true
    cxt.drawImage(this.img, this.x, this.y, this.w, this.h)
    if (this.isspacing) {
      cxt.fillStyle = 'rgba(0, 0, 0, 0.5)'
      cxt.fillRect(this.x, this.blacky, this.w, this.blackh)
    } else {
      deltaTime = 0
      self.hasCollided = false
      self.blackh = self.h
      self.blacky = self.y
    }
    cxt.fillStyle = 'black'
    cxt.font = '24px Microsoft YaHei'
    cxt.fontWeight = 700
  }

  startCooldown() {
    if (this.timer) clearInterval(this.timer)
    if (this.isspacing) {
      this.timer_num = this.timer_spacing / 1000
      this.timer = setInterval(() => {
        if (this.timer_num > 0) {
          this.timer_num--
        } else {
          clearInterval(this.timer)
          this.timer = null
          this.isspacing = false
        }
      }, 1000);
    }

  }
}


//绘制铲子对像
class Shovel {
  constructor() {
    let s = {
      shovelimg: null,
      shovebg: null,
      x: 1000,
      y: 0,
      isClick: false
    }
    Object.assign(this, s)
  }

  static new() {
    let s = new this()
    s.init()
    return s
  }

  init() {
    let self = this
    self.shovelimg = getImageBySrc(allImgSrcObj.shovel)
    self.shovebg = getImageBySrc(allImgSrcObj.shovelbg)
  }
  draw(cxt) {
    let self = this
    cxt.drawImage(self.shovebg, 1000, 0, 90, 45)
    cxt.drawImage(self.shovelimg, self.x + 5, self.y + 5, 76, 34)
  }
}

class Car {
  constructor(info) {
    let c = {
      carImg: null,
      x: info.x,
      y: info.y,
      col: info.col,
      row: info.row,
      canRun: false,
      //判断该小车是否存在
      isExist: true
    }
    Object.assign(this, c)
  }

  static new(info) {
    let c = new this(info)
    c.init()
    return c
  }

  init() {
    let self = this
    self.carImg = getImageBySrc(allImgSrcObj.car)
    // console.log(self.carImg)
  }

  update() {
    let self = this
    //判断是否有僵尸超过界限
    if (self.canRun && self.isExist) {
      self.x += 2
    }


  }

  draw(cxt) {
    let self = this
    if (self.carImg instanceof HTMLImageElement) {
      cxt.drawImage(self.carImg, self.x, self.y, 70, 57)
    }
  }
}

//创建阳光类
class sunNum {
  constructor() {
    let s = {
      img: null,
      sun_num: window.main.allSun,
      x: 0,
      y: 0
    }
    Object.assign(this, s)
  }

  //创建并初始化该对象
  static new() {
    let s = new this()
    return s
  }



  draw(cxt) {
    let self = this
    cxt.fillStyle = 'black';
    // 设置字体和字体粗细
    cxt.font = '700 20px Microsoft YaHei';
    // 使用 this 访问当前对象的属性
    if (self.sun_num === 0) {
      cxt.fillText(self.sun_num, self.x + 32, self.y + 74);
    } else if (self.sun_num >= 100 && self.sun_num < 1000) {
      cxt.fillText(self.sun_num, self.x + 20, self.y + 74);
    } else if (self.sun_num < 100 && self.sun_num > 0) {
      cxt.fillText(self.sun_num, self.x + 24, self.y + 74);
    } else if (self.sun_num >= 1000) {
      cxt.fillText(self.sun_num, self.x + 12, self.y + 74);
    }

  }

  //改变阳光的值
  changeSunNum(num = 25) {
    let g = this
    window.main.allSunVal += num
    g.sun_num += num
    window.main.allSun += num
  }

}


//创建植物和僵尸的父类
class Obj {
  constructor(obj) {
    let o = {
      //类型（向日葵，豌豆）
      section: obj.section,
      x: obj.x,
      y: obj.y,
      row: obj.row,
      col: obj.col,
      w: 0,
      h: 0,
    }
    Object.assign(this, o)
  }

}

//创建植物对象
class Plant extends Obj {
  constructor(obj) {
    super(obj)
    //创建植物私有属性
    let p = {
      //定义植物储存图片
      sunid: 0,
      images: {},
      life: 3,
      attack: null,
      digest: null,
      shoot: null,
      isdigest: false,
      bullet: [],
      canShoot: false,
      canSetTimer: obj.canSetTimer,
      sunTimer: null,
      sunTimer_spacing: 15,
      currentAction: 'idle',
      currentIndex: 0,
      //设置上一次更新时间
      lastUpdateTime: 0,
      //时间频差
      frameRate: 5,
      hasCollided: false,
      lastUpdateTimechomper: 0,
      lastUpdateTimepeashooter: 0,
      count: 0,
      sunTimer: null,
      sun_spacing: 50,
      has: false,
    }
    Object.assign(this, p)
  }


  //创建并初始化对象
  static new(obj) {
    let p = new this(obj)
    p.init(obj)
    return p
  }

  init(obj) {
    let self = this
    //如果该植物为坚果，初始化血量为9
    self.h = 73
    self.w = 74
    self.sunid = Math.floor(Math.random() * 10000) + 1;
    //添加图片
    if (obj.section === 'sunflower') {
      self.frameRate = 15
      self.images = {
        idle: [],
      }
      self.setSunTimer()
      self.loadImages('idle', obj.section)
    }
    if (obj.section === 'peashooter') {
      self.canShoot = true
      self.w = 71
      self.h = 71
      self.images = {
        idle: [],
        attack: [],
      }
      self.loadImages('idle', obj.section)
      self.loadImages('attack', obj.section)
    }
    if (obj.section === 'cherrybomb') {
      self.w = 112
      self.h = 81
      self.images = {
        idle: [],
        attack: [],
      }
      self.loadImages('idle', obj.section)
      self.loadImages('attack', obj.section)
    }
    if (obj.section === 'wallnut') {
      this.w = 65
      this.h = 73
      this.currentAction = 'idleH'
      this.life = 9
      this.frameRate = 15
      self.images = {
        idleH: [],
        idleM: [],
        idleL: []
      }
      self.loadImages('idleH', obj.section)
      self.loadImages('idleM', obj.section)
      self.loadImages('idleL', obj.section)
    }

    if (obj.section === 'chomper') {
      this.h = 114
      this.w = 130
      self.images = {
        idle: [],
        attack: [],
        digest: []
      }
      self.loadImages('idle', obj.section)
      self.loadImages('attack', obj.section)
      self.loadImages('digest', obj.section)
    }
  }

  loadImages(action, section) {
    let self = this;
    const { src, len } = allImgSrcObj.plants[section][action];
    for (let i = 0; i < len; i++) {
      const img = new Image()
      img.src = './images/' + src.replace('*', i.toString().padStart(2, '0')); // 确保数字格式为两位数
      img.onload = () => {
        self.images[action][i] = img // 修正了索引错误
      };
    }
  }

  draw(cxt) {
    let self = this
    const now = Date.now();
    // 计算时间差
    const deltaTime = now - self.lastUpdateTime;
    // 每帧更新间隔（毫秒）
    const frameInterval = 1000 / self.frameRate;

    if (deltaTime >= frameInterval) {
      self.lastUpdateTime = now;
      // 更新图片索引
      self.currentIndex = (self.currentIndex + 1) % self.images[self.currentAction].length || 0;
      // 绘制当前图片
    }
    //确保图片已经加载
    const img = self.images[self.currentAction][self.currentIndex];
    if (img instanceof HTMLImageElement) {
      cxt.drawImage(img, self.x, self.y, self.w, self.h); // 根据实际需要调整宽高
    }
  }

  // 删除一个植物
  removePlant(plant) {
    let main = window.main
    // 从数组中找到并移除植物
    const index = main.plants.indexOf(plant);
    if (index !== -1) {
      main.plants.splice(index, 1); // 从数组中移除植物
    }
  }

  //判断豌豆射手是否可发射子弹
  isShoot() {
    for (let zombie of window.main.zombies) {
      // 判断植物是否可以射击
      if (this.row === zombie.row && this.x <= zombie.x && zombie.x <= 830) {
        return true;
      }
    }
    return false;
  }

  clearsunTimer() {
    if (this.sunTimer) {
      clearInterval(this.sunTimer)
      this.sunTimer = null
    }

  }

  //生成阳光计时器
  setSunTimer() {
    let self = this
    self.sunTimer = setInterval(function () {
      let img = document.createElement('img')
      img.src = 'images/Sun.gif'
      let container = document.querySelector('.game-jframe')
      // 随机生成太阳图片的位置
      let maxX = self.x - 5; // 减去图片宽度以避免超出容器
      let maxY = self.y; // 减去图片高度以避免超出容器
      // let randomX = Math.random() * maxX;
      // let randomY = Math.random() * maxY;
      img.style.top = `${maxY}px`;
      img.style.left = `${maxX}px`;
      img.className = 'sun'
      container.appendChild(img)
      window.main.allSun += 25
      img.addEventListener('animationend', function () {
        if (img.parentNode) {
          img.parentNode.removeChild(img);
        }
      });

    }, self.sunTimer_spacing * 1000)
  }

  // 更新植物状态
  update() {
    let self = this;
    let main = window.main;
    const now = Date.now();
    // 计算时间差
    const deltaTimeChomper = now - self.lastUpdateTimechomper;
    const deltaTimePeashooter = now - self.lastUpdateTimepeashooter;
    // 每帧更新间隔（毫秒）
    const frameInterval = 1000 / self.frameRate;

    // 清除生命值为负的植物
    for (let plant of main.plants) {
      if (plant.life < 0) {
        if (plant.section === 'sunflower') {
          plant.clearsunTimer()
        }
        this.removePlant(plant);
      }
    }
    console.log(self.isCollision())
    // 处理不同植物类型的状态
    if (self.section === 'wallnut') {
      if (self.life >= 6 && self.life <= 9) {
        self.currentAction = 'idleH';
      } else if (self.life >= 2 && self.life < 6) {
        self.currentAction = 'idleM';
      } else if (self.life >= 0 && self.life < 2) {
        self.currentAction = 'idleL';
      }
    }
    if (self.section === 'cherrybomb') {
      if (self.currentAction == 'idle') {
        if (self.currentIndex == self.images.idle.length - 1) {
          self.currentAction = 'attack';
          self.currentIndex = 0;
          // console.log("樱桃炸弹播放完 idle 动画，切换到 attack 动画");
        }
      } else if (self.currentAction == 'attack') {
        if (self.currentIndex == self.images.attack.length - 1) {
          self.life = -1;
          // console.log('樱桃炸弹播放完 attack 动画，设置生命值为 -1');
        }
      }
    }
    if (self.section === 'chomper') {
      // 播放消化动画并减少僵尸生命值
      if (self.currentIndex === self.images.digest.length - 1 && self.isdigest) {
        if (self.count < 10) {
          if (deltaTimeChomper > frameInterval) {
            self.count++
            // console.log(self.count)
            self.lastUpdateTimechomper = now
          }
        } else {
          // 消化动画播放完毕，切换到 idle 状态
          self.currentAction = 'idle'; // 重置为 idle 状态
          self.isdigest = false; // 标记为未消化
          self.count = 0
        }
      }
    }
    if (self.section === 'peashooter') {
      // 更新子弹位置和检查碰撞
      for (let i = this.bullet.length - 1; i >= 0; i--) {
        let bullet = this.bullet[i];
        // 如果子弹需要移除或者超出屏幕范围，删除子弹
        if ((!(bullet.toRemove) && bullet.x > window.innerWidth) || bullet.bulletImg === getImageBySrc(allImgSrcObj.bulletHit)) {
          this.bullet.splice(i, 1); // 从数组中移除子弹
        }
      }
      //判断是否可射击J（僵尸是否在同行）
      if (self.isShoot()) {
        if (deltaTimePeashooter > frameInterval * 38) {
          self.bullet.push(Bullet.new(self))
          self.lastUpdateTimepeashooter = now
        }
      }
    }
  }
  //碰撞事件
  isCollision() {
    let self = this
    let main = window.main
    for (let zombie of main.zombies) {
      console.log(zombie.row, self.row, self.x, zombie.x)
      if (zombie.row === self.row && self.x - zombie.x <= 30 && self.x - zombie.x > 10) {
        return zombie
      }
    }
    return null
  }
}

class Bullet {
  constructor(plant) {
    let b = {
      bulletImg: getImageBySrc(allImgSrcObj.bullet),
      w: 40,
      h: 40,
      x: 0,
      y: 0,
      col: plant.col,
      row: plant.row,
      speed: 4,
      lastUpdateTime: 0,
      frameRate: 5,
      canRemove: false,
      isHurt: false,
      hasCollided: false,
    }
    Object.assign(this, b)
  }

  static new(plant) {
    let b = new this(plant)
    //初始化坐标
    switch (plant.section) {
      case 'peashooter':
        b.x = plant.x + 30
        b.y = plant.y
    }
    return b
  }


  update() {
    let self = this
    const now = Date.now();
    // 计算时间差
    let deltaTime
    const frameInterval = 300 / self.frameRate;
    self.x += self.speed
    let zombie = self.checkCollision()
    if (zombie && self.bulletImg) {
      self.canRemove = true
      self.bulletImg = getImageBySrc(allImgSrcObj.bulletHit)
      if (!self.hasCollided) {
        self.lastUpdateTime = now
        self.hasCollided = true
      }

      if (!self.isHurt && zombie.life > 1) {
        zombie.life--
        self.isHurt = true
      }
      deltaTime = now - self.lastUpdateTime;
      if (deltaTime > frameInterval) {
        self.bulletImg = null
      }
    }


  }

  draw(cxt) {
    let self = this

    if (self.bulletImg instanceof HTMLImageElement) {
      cxt.drawImage(self.bulletImg, self.x, self.y); // 根据实际需要调整宽高
    }
  }

  // 检查子弹是否与僵尸碰撞
  checkCollision() {
    let self = this;
    for (let zombie of window.main.zombies) {
      if (zombie.row === self.row && self.x - zombie.x > 40) {
        return zombie; // 返回发生碰撞的僵尸
      }
    }
    return null; // 没有碰撞
  }

}

class Zombie extends Obj {
  constructor(obj) {
    super(obj);
    let z = {
      images: {
        idle: [],
        run: [],
        attack: [],
        dieboom: [],
        dying: { head: [], body: [] },
        die: []
      },
      life: 9,
      canSetTimer: obj.canSetTimer,
      currentAction: 'idle',
      //是否改变状态
      hasCollided: false,
      //正常情况下只有一个图片
      currentIndex: 0,
      //僵尸头掉落情况
      // headcurrentIndex: 0,
      bodycurrentIndex: 0,
      //更新图片最后一频
      lastUpdateTimeImg: 0,
      //樱桃炸弹的最后一频
      lastUpdateTimecherry: 0,
      //食人花的最后一频
      lastUpdateTimechomper: 0,
      //其他植物的最后一频
      lastUpdateTime: 0,
      frameRate: 7,
      attack: null,
      state_now: 0,
      state_idle: 0,
      state_run: 1,
      state_attack: 2,
      state_die: 4,
      state_dieboom: 5,
      hasCurrentIndex: false
    };
    Object.assign(this, z);
  }

  static new(obj) {
    let z = new this(obj);
    z.init();
    return z;
  }

  init() {
    let self = this;
    self.w = 166;
    self.h = 144
    self.loadImages('idle');
    self.loadImages('run');
    self.loadImages('attack');
    self.loadImages('dieboom');
    self.loadImages('die')

    // console.log('self.images:' + self.images);
  }

  loadImages(action) {
    let self = this;
    if (!self.images[action]) {
      self.images[action] = [];
    }
    const { src, len } = allImgSrcObj.zombies[action];
    for (let i = 0; i < len; i++) {
      const img = new Image();
      img.src = './images/' + src.replace('*', i.toString().padStart(2, '0'));
      img.onload = () => {
        self.images[action][i] = img;
      };
    }
  }


  draw(cxt) {
    let self = this;
    const now = Date.now();
    const deltaTime = now - self.lastUpdateTimeImg;
    const frameInterval = 1000 / self.frameRate;

    if (deltaTime >= frameInterval) {
      self.lastUpdateTimeImg = now;
      const imgArray = self.images[self.currentAction];
      if (imgArray) {
        if ((self.state_now === self.state_idle) || (self.state_now === self.state_die) || (self.state_now === self.state_run) || (self.state_now === self.state_attack) || (self.state_now === self.state_dieboom)) {
          if (imgArray.length > 0) {
            self.currentIndex = (self.currentIndex + 1) % imgArray.length;

          }
        }

      }
    }

    const imgArray = self.images[self.currentAction];
    if ((self.state_now === self.state_idle) || (self.state_now === self.state_die) || (self.state_now === self.state_run) || (self.state_now === self.state_attack) || (self.state_now === self.state_dieboom)) {
      const img = imgArray[self.currentIndex];
      if (img instanceof HTMLImageElement) {
        cxt.drawImage(img, self.x, self.y, self.w, self.h);
      }
    }

  }

  // 删除一个僵尸
  removeZombie(zombie) {
    let main = window.main
    // 从数组中找到并移除植物
    const index = main.zombies.indexOf(zombie);
    if (index !== -1) {
      main.zombies.splice(index, 1); // 从数组中移除植物
    }
  }

  update() {
    let self = this;
    let main = window.main;
    const now = Date.now();
    const deltaTime = now - self.lastUpdateTime;
    const deltaTimeCherry = now - self.lastUpdateTimecherry;
    const deltaTimeChomper = now - self.lastUpdateTimechomper;
    const frameInterval = 1000 / self.frameRate;

    // 生命值为0的僵尸清除
    main.zombies = main.zombies.filter(zombie => zombie.life >= 0);

    // 僵尸的移动
    if (self.currentAction === 'idle' || self.currentAction === 'run') {
      self.x -= 0.11;
    } else if (self.currentAction === 'die') {
      self.x -= 0.05
    }

    for (let car of main.cars) {
      if (car.x >= 1120) {
        car.isExist = false
      }
      // console.log(car.canRun)
      if (self.x + 20 < car.x && car.isExist && self.row === car.row) {
        car.canRun = true
        self.life = 1
      }
    }

    self.col = Math.ceil(self.x / 100);

    // 碰撞检测
    let plant = this.isCollision();
    if ((plant !== null && self.life >= 1)) {
      if (['wallnut', 'sunflower', 'peashooter'].includes(plant.section)) {
        // 攻击植物
        self.state_now = self.state_attack;
        self.currentAction = 'attack';
        if (deltaTime >= frameInterval * 15) {
          self.lastUpdateTime = now;
          plant.life--;
          if (plant.life <= 0) {
            self.currentAction = 'idle';
            self.state_now = self.state_idle;
          }
        }
      } else if (plant.section === 'cherrybomb') {
        if (!self.hasCollided) {
          self.currentIndex = 0;
          self.hasCollided = true;
        }
        if (self.currentAction === 'idle' && plant.currentIndex === plant.images.idle.length - 1) {
          self.state_now = self.state_dieboom;
          self.currentAction = 'dieboom';
          self.currentIndex = 0;
          plant = null;
          self.hasCollided = false;
        }

      } else if (plant.section === 'chomper' && self.life > 1) {
        if (!plant.isdigest) {
          if (plant.currentAction === 'idle') {
            plant.currentIndex = 0;
            plant.currentAction = 'attack'

          }
          if (plant.currentAction === 'attack' && plant.currentIndex >= plant.images.attack.length - 1) {
            plant.currentAction = 'digest';
            self.life = -1;
            plant.isdigest = true;
            plant.currentIndex = 0;
          }
        } else {
          self.currentAction = 'attack';
          self.state_now = self.state_attack;
          if (deltaTimeChomper > frameInterval * 15) {
            self.lastUpdateTimechomper = now;
            plant.life--;
            if (plant.life <= 0) {
              self.currentAction = 'idle';
              self.state_now = self.state_idle;
            }
          }
        }


      }
    } else {
      if (self.currentAction === 'dieboom') {
        console.log(self.currentIndex)
        if (self.currentIndex >= self.images.dieboom.length - 1) {
          self.hasCollided = false;
          self.life = -1;
        }
      } else if (self.life > 1) {
        self.currentAction = "idle"
      } else if (self.life <= 1) {
        self.currentAction = 'die';
        self.state_now = self.state_die;
        if (!self.hasCollided) {
          self.currentIndex = 0
          self.hasCollided = true
        }
        // console.log('bodycurrentIndex' + self.currentIndex)
        if (self.currentIndex === self.images.die.length - 2) {
          self.hasCollided = false
          self.life = -1
        }
      }
    }
  }

  //碰撞事件
  isCollision() {
    let self = this
    let main = window.main
    for (let plant of main.plants) {
      if (self.life > 1) {
        if (plant.section === 'chomper' && self.life > 1 && plant.row === self.row && plant.x - self.x <= 40 && plant.x - self.x > 10) {
          return plant
        }
        else if (plant.row === self.row && self.life - 1 > 1 && plant.x - self.x <= 90 && plant.x - self.x > 30) {
          return plant
        }
      }
    }
    return null
  }


}






